package com.propertyportal.propertylistfragment;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Gallery;
import android.widget.ListView;
import android.widget.TextView;

import com.actionbarsherlock.app.SherlockFragment;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import com.personhelper.PersonHelper;
import com.propertyportal.alladapter.PropertyAgentListAdapter;
import com.propertyportal.manageproperty.ManageProperty;
import com.propertyportal.manageproperty.R;
import com.propertyportal.propertylist.ImageLoader;


public class PropertyDetail extends SherlockFragment{

	int curIndex=0;
	int downX,upX;
    private TextView title;
    private TextView price;
    private TextView type;
    private TextView description;
    private TextView address;
	public Gallery g;
    public String mobilenumber;
    public String landline;
    public String contacts;
    public String email;
    public String name;
    public String status;
    public final static String ARG_POSITION = "position";
    public static int mCurrentPosition = -1;
    public ImageLoader imageLoader;
    public int prop_id=0;
    public int property_id=0;
	public Context appContext;
	public HashMap<String, String> map;
	public Bitmap[] bitmapimage;
	public static ArrayList<String> images;

	public PropertyAgentListAdapter pa;
	private ListView propertyagentlist;		
	public Context context;
	public List<PersonHelper> tobedisplay=new ArrayList<PersonHelper>();
	public static int extraposition=0;
	public PersonHelper ph;

	
    @Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    	
		if (savedInstanceState != null) {
            mCurrentPosition = savedInstanceState.getInt(ARG_POSITION);
        }
		context = getActivity().getApplicationContext();
		images=new ArrayList<String>();

		View view=inflater.inflate(R.layout.view_property, container, false);
		
        title=(TextView)view.findViewById(R.id.detail_title);
        price=(TextView)view.findViewById(R.id.detail_price);
        type=(TextView)view.findViewById(R.id.detail_type);
        tobedisplay.clear();
        propertyagentlist=(ListView)view.findViewById(R.id.propertyagentlist);
        pa=new PropertyAgentListAdapter(context,tobedisplay);
        
        address=(TextView)view.findViewById(R.id.detail_address);
        description=(TextView)view.findViewById(R.id.detail_description);

        imageLoader=new ImageLoader(getActivity().getApplicationContext());
        propertyagentlist.setOnTouchListener(new ListView.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                int action = event.getAction();
                switch (action) {
                case MotionEvent.ACTION_DOWN:
                    // Disallow ScrollView to intercept touch events.
                    v.getParent().requestDisallowInterceptTouchEvent(true);
                    break;

                case MotionEvent.ACTION_UP:
                    // Allow ScrollView to intercept touch events.
                    v.getParent().requestDisallowInterceptTouchEvent(false);
                    break;
                }

                // Handle ListView touch events.
                v.onTouchEvent(event);
                return true;
            }
        });
        new LoadData().execute();
        setHasOptionsMenu(true);
        
        return view;
    }
    @Override
    public void onStart() {
    	// TODO Auto-generated method stub
    	super.onStart();
    	Bundle args = getArguments();
        if (args != null) {
        updateViewShowDetail(args.getInt(ARG_POSITION));	
        
        }
    }
    public void display(){
    	String result=getAllProperty(PropertyList.property.get(ManageProperty.clickposition).getPropertyId());
    	
    	if (result != null) {
			
    		try {
    			
			JSONArray array = new JSONArray(result);
		
				for (int i = 0; i < array.length(); i++) {
					JSONObject e = array.getJSONObject(i);
					
					JSONArray contacts=e.getJSONArray("contactsCollection");
					
					for(int j=0;j<contacts.length();j++){
						JSONObject c=contacts.getJSONObject(j);
						 ph=new PersonHelper(e.getString(PropertyList.KEY_FNAME),e.getString(PropertyList.KEY_LNAME),
								 c.getString(PropertyList.KEY_EMAIL),c.getString(PropertyList.KEY_LANDLINE),c.getString(PropertyList.KEY_MOBILE));
					}
					tobedisplay.add(ph);
				}
				
			} catch (JSONException e) {
				Log.e("log_tag", "Error parsing data " + e.toString()
						+ "diri jud");
			} finally {

			}
			//adapter = new PropertyListAdapter(getActivity(), property);

		} else {
			// Toast.makeText(getActivity(), "No data",
			// Toast.LENGTH_LONG).show();
		}
    }
    public String getAllProperty(int id){
		String urls = "http://192.168.2.38:8080/STTHERESEREALTYWS/webresources/com.propertyportal.entities.property/getAllAgentProperty/";

	    String json = "";
		try {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpGet httpPost = new HttpGet(urls+id);
 
            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
           // is = httpEntity.getContent();          
            json = EntityUtils.toString(httpEntity);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
              
        return json;
	    } 
   
    public void updateViewShowDetail(int position){
    	Resources res = getResources();
    	String[] types = res.getStringArray(R.array.propertyType);
    	try{
    	Locale ph=new Locale("en","Philippines");
    	NumberFormat defaultFormat = NumberFormat.getCurrencyInstance(ph);
    	double presyo=Double.parseDouble(PropertyList.property.get(position).getPrice());
    	price.setText("Price: "+defaultFormat.format(presyo));
    	}catch(NumberFormatException num){
    		//Log.d("err", num.getMessage());
    	}
    	title.setText("Name: "+ PropertyList.property.get(position).getName());
    	type.setText("Type: "+types[PropertyList.property.get(position).getType()]);
    	
    	description.setText(PropertyList.property.get(position).getDescription());
    	address.setText("Address:"+PropertyList.property.get(position).getAddress());
    	
    	mCurrentPosition = position;
    	   	    	
    }
    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    	// TODO Auto-generated method stub
    	super.onCreateOptionsMenu(menu, inflater);
    	//menu.clear();
    	inflater.inflate(R.menu.detail, menu);
    	
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
    	// TODO Auto-generated method stub
    	switch(item.getItemId()){
    	case R.id.update:
    		EditProperty pd=(EditProperty)getFragmentManager().findFragmentById(R.id.article_fragment);
    		if(pd!=null){
    			pd.displayData(mCurrentPosition);
    			ManageProperty.clickposition=mCurrentPosition;
    		}
    		else {
                // If the frag is not available, we're in the one-pane layout and must swap frags...

                // Create fragment and give it an argument for the selected article
                
                Bundle args = new Bundle();
                EditProperty pvd=new EditProperty();
                args.putInt(EditProperty.ARG_POSITION, mCurrentPosition);
                pvd.setArguments(args);
                FragmentTransaction transaction = getFragmentManager().beginTransaction();

                // Replace whatever is in the fragment_container view with this fragment,
                // and add the transaction to the back stack so the user can navigate back
                transaction.replace(R.id.fragment1, pvd);
                transaction.addToBackStack(null);
                
                ManageProperty.clickposition=mCurrentPosition;
                // Commit the transaction
                transaction.commit();
            }
    		
    		return true;
    	case R.id.delete:
           
            DeleteProperty dl=new DeleteProperty();
            dl.execute(PropertyList.property.get(mCurrentPosition).getPropertyId());
            
            FragmentManager fm = getActivity().getSupportFragmentManager();
			fm.popBackStack();
    		
    		return true;
    	default:
    		return super.onOptionsItemSelected(item);
    	}
    }
    
    private class LoadData extends AsyncTask<Void, Void, Void> {


		protected void onPreExecute() {
		}

		@Override
		protected Void doInBackground(final Void... unused) {

			try {
				display();

			} catch (Exception e) {
				Log.e("", "wala jud ma add", e);
			}
			return null;
		}

		protected void onPostExecute(Void result) {
			propertyagentlist.setAdapter(pa);
			//Toast.makeText(getActivity(), property.toString(), Toast.LENGTH_LONG).show();
		}

	}

}
